class TitlesController < ApplicationController
  before_filter :login_required
  
  def destroy
    @title = Title.find(params[:id])
    @character = @title.character
    
    title_name = @title.name
    respond_to do |format|
      if @title.revoke
        flash[:notice] = "Title of #{title_name} revoked from #{@character.name}"
        format.html { redirect_to @character }
        format.js
      else
        flash[:notice] = "Failed to revoke title of #{title_name} from #{@character.name}"
        format.html { redirect_to @character }
        format.js
      end
    end
  end
  
  
  
  def create
    @title = Title.new(params[:title])
    @character = @title.character
    title_name = @title.name
    pc = current_player.player_character
    if @title.grantable?(pc, @character)
      @title = Title.grant_title(@character, @title.category, @title.sub_category, @title.domain)
    else
      @title = nil
    end
    respond_to do |format|
      if @title
        flash[:notice] = "#{@character.name} given title of #{title_name}"
        format.html { redirect_to @character }
        format.js
      else
        flash[:notice] = "Failed to give title of #{title_name} to #{@character.name}"
        format.html { redirect_to @character }
        format.js
      end
    end
  end
  
  def update
    @title = Title.find(params[:id])
    @character = Character.find(params[:character_id])
    title_name = @title.name
    pc = current_player.player_character
    if @title.grantable?(pc, @character)
      @title = Title.grant_title(@character, @title.category, @title.sub_category, @title.domain)
    else
      @title = nil
    end
    respond_to do |format|
      if @title
        flash[:notice] = "#{@character.name} given title of #{title_name}"
        format.html { redirect_to @character }
        format.js
      else
        flash[:notice] = "Failed to give title of #{title_name} to #{@character.name}"
        format.html { redirect_to @character }
        format.js
      end
    end
  end
end
